/**
 * Created by mac on 15-10-23.
 */
$.fn.comments = function( settings ) {

    var $this = $(this),
        autoOpen = settings && settings.autoOpen == true;



    //事件委托 点击展开评论
    $this.on('click', '.title', function() {
        openComment($(this));
    });


    //事件委托 评论微博 输入框
    $this.on('keydown', '.js-cumment-input', function() {
        var thisInput = $(this),
            oSubmit = thisInput.parents('.textarea').eq(0).siblings('.button').find('.js-cumment-button');

        inputRule(thisInput, oSubmit);
    });
    $this.on('keyup', '.js-cumment-input', function() {
        var thisInput = $(this),
            oSubmit = thisInput.parents('.textarea').eq(0).siblings('.button').find('.js-cumment-button');

        inputRule(thisInput, oSubmit);
    });


    //事件委托 点击评论微博
    $this.on('click', '.js-cumment-button', function() {
        var userInfo = userServers.getUserInfo();

        if ( userInfo.userName ) {
            var thisButton = $(this),
                userAvatar = userInfo.userAvatar,
                userName = userInfo.userName;
            if ( !thisButton.hasClass('button-disabled') ) { //如果该按钮可点击
                var oListUl = thisButton.parents('.content').eq(0).find('.list ul'),
                    oInput = thisButton.parents('.input-block').find('.js-cumment-input'),
                    ugcId = thisButton.parents(" .clearfix").attr('_ugcid'),
                    replayUserId = thisButton.parents(" .clearfix").attr('_replayUserId'),
                    ugcType = thisButton.parents(" .clearfix").attr('_ugctype');

                //添加一条评论
                var data = {
                    'commentAvatar': userAvatar,
                    'commentUserName': userName,
		            'commentUserId': userInfo.userId,
                    'commentPublishTime': '刚刚',
                    'ugcId':ugcId,
                    'replayUserId':replayUserId,
                    'ugcType':ugcType,
                    'commentContent': oInput.val()
                };

                //向后端插入该条评论
                commentServers.addFirstComment(data, function( msg ) {
                    if ( !msg.error ) {
                        //成功之后前端显示评论内容
                        $.extend(msg, data);
                        addComment(oListUl, msg.detail);
                    } else {
                        window.globalLayer.openWarning({'autoClose':true, time: 2000, text:msg.description});
                    }
                });

                oInput.val('');
                thisButton.addClass('button-disabled');
            }
        } else {
            window.globalLayer.openLogin(); //打开登陆提示弹窗
        }
    });


    //事件委托 点击回复评论 添加回复框和回复按钮
    $this.on('click', '.reply', function() {
        var userInfo = userServers.getUserInfo();

        if ( userInfo.userName ) {
            var thisReplay = $(this),
                oParent = thisReplay.parents('.con').eq(0);

            //如果是第一次点击
            if ( !thisReplay.data('hasAppend') ) {
                addReply( oParent );
                thisReplay.data('hasAppend', true);
            }
        } else {
            window.globalLayer.openLogin(); //打开登陆提示弹窗
        }
    });


    //事件委托 回复评论输入框
    $this.on('keydown', '.js-input-reply', function() {
        var thisInput = $(this),
            oSubmit = thisInput.parents('.textarea').siblings('.button').find('.js-button-submitreply');

        inputRule(thisInput, oSubmit);
    });
    $this.on('keyup', '.js-input-reply', function() {
        var thisInput = $(this),
            oSubmit = thisInput.parents('.textarea').siblings('.button').find('.js-button-submitreply');

        inputRule(thisInput, oSubmit);
    });


    //事件委托 点击回复提交按钮 完成回复内容
    $this.on('click', '.js-button-submitreply', function() {
        var userInfo = userServers.getUserInfo();

        if ( userInfo.userName ) {
            var thisButton = $(this),
                userAvatar = userInfo.userAvatar,
                userName = userInfo.userName;

            if ( !thisButton.hasClass('button-disabled') ) {
                var oListUl = thisButton.parents('.list ul'),
                    oInput = thisButton.parents('.textarea-block').find('.js-input-reply'),
                    replyUserName = thisButton.parents('.con').find('.user-name').eq(0).find('a').text(),
                    uid = thisButton.parents('.con').attr('uid'),
                    cid = thisButton.parents('.con').attr('cid'),
                        replayUserId = thisButton.parents('.con').attr('replayUserId'),
                    ugcId = thisButton.parents('.con').attr('ugcId');
                    //回复用户者的id。需要在.con中添加userId方便回复的时候填写

                //添加一条微博评论
                //向后端插入该条评论
                var args = {
                    'commentAvatar': userAvatar,
                    'commentUserName': userName,
                    'commentUserId': userInfo.userId,
                    'commentReplyUserName': replyUserName,
                    'ugcId':ugcId,
                    'cid':cid,
                    'uid': uid,
                    'replayUserId': uid,
                    'commentPublishTime': '刚刚',
                    'isReply': true,
                    'commentContent': oInput.val()
                };
                commentServers.addComment(args, function(msg) {
                    if ( !msg.error ) {
                        $.extend(msg, args);
                        addComment(oListUl, msg.detail); //前端显示评论内容
                        oInput.val('');
                        thisButton.addClass('button-disabled');
                    } else {
                        window.globalLayer.openWarning({'autoClose':true, time: 2000, text:msg.description});
                    }
                });
            }
        } else {
            window.globalLayer.openLogin(); //打开登陆提示弹窗
        }
    });


    //事件委托 点击删除评论或微博
    $this.on('click', '.js-remove-comment', function() {
        var userInfo = userServers.getUserInfo();

        if ( userInfo.userName ) {
            var thisDel = $(this),
                oParentLi = thisDel.parents('li').eq(0);

            //打开删除提示窗
            window.globalLayer.openDelete({'callBack': function(canDel) {

                if ( !canDel ) return;
                //通知后端删除id为xxx的评论
                commentServers.removeComment({
                    'cid': oParentLi.attr('cid'),
                    'ugcType': thisDel.parents('li').eq(1).attr('_ugctype')
                }, function(msg) {
                    if ( !msg.error ) {
                        removeComment(oParentLi);
                    } else {
                        window.globalLayer.openWarning({'autoClose':true, time: 2000, text:msg.description});
                    }
                });

            }});

        } else {
            window.globalLayer.openLogin(); //打开登陆提示弹窗
        }
    });


    //事件委托 点击评论的分页页码切换评论数据
    $this.on('click', '.page a', function() {
        var thisTab = $(this),
            oPage = thisTab.parent(),
            currentPageStep = 0;

        if ( !oPage.data('pageStep') ) { oPage.data('pageStep', 1) } //默认pageStep是1，代表第一页
        currentPageStep = oPage.data('pageStep');

        if ( thisTab.hasClass('pre') ) {

            //用户点击了上一页
            if ( currentPageStep > 1 ) {
                oPage.data('pageStep', currentPageStep-1);
            }

        } else if ( thisTab.hasClass('next') ) {

            //用户点击了下一页
            oPage.data('pageStep', currentPageStep+1);

        } else {

            //用户点击了分页的页码数，如点击了 1、 2、 3 。。。
            //oPage.data( 'pageStep', Number(thisTab.text()) );

        }

        insertCommentContent(thisTab, oPage.data('pageStep')); //插入评论数据
    });


    //////////////////////////////////////////////////////
    //打开评论区
    function openComment( thisTit ) {
        if ( !thisTit.hasClass('no-h') ) { //当前可点击展开
            thisTit.addClass('no-h').find('i').remove();
            insertCommentContent(thisTit, 1); //插入评论数据
        }
    }
    //自动打开评论区
    function autoOpenComment() {
        openComment($this.find('li').eq(0).find('.title'));
    };


    //输入框内容的规则限制
    function inputRule( $input, $button ) {
        //限制字数
        $.maxTextLen({
            'field': $input,
            'isSubStr': true,
            'callBack': function(data) {
                //是否激活提交按钮
                canActiveButton($button, data);
            }
        });
    }


    //判断是否能激活按钮
    function canActiveButton( $obj, boolean ) {
        if ( boolean ) {
            $obj.removeClass('button-disabled');
        } else {
            $obj.addClass('button-disabled');
        }
    }


    //添加回复评论的 输入框 和 回复按钮 html
    function addReply( $obj ) {
        $obj.append(
            '<div class="textarea-block">\
                <div class="textarea"><textarea class="js-input-reply" name=""></textarea></div>\
                <div class="button"><button type="button" class="js-button-submitreply button-default button-disabled">回复</button></div>\
            </div>'
        );
    }


    //添加一条评论html
    function addComment( $obj, data ) {
        $obj.prepend( getCommentContentHtml(data) );
    }


    //删除一条评论
    function removeComment( $obj ) {
        $obj.remove();
    }


    //插入评论数据
    function insertCommentContent( $thisTab, pageStep ) {
        //获取评论数据
        commentServers.getCommentDatas({
            'ugcid': $thisTab.parents('li').attr('_ugcid'), //该条ugc的id值
            'pageStep': pageStep, //当前分页的区间，从1开始，代表第一页
            'count': 10 //每次请求时获取的微博条数 即每页条数
        }, function( msg ) {
            if ( !msg.error ) {
                if ( msg.code == 200 ) {
                    var oCommentBox = $thisTab.parents('.comment').eq(0);

                    //如果是第一次加载数据
                    if ( !oCommentBox.data('banInsertBox') ) {
                        oCommentBox.append( getCommentBoxHtml() ); //插入评论的总体html框架
                        oCommentBox.data('banInsertBox', true);
                    }

                    var oCommentList = oCommentBox.find('.js-comment-list'),
                        oUl = oCommentList.find('ul'),
                        oPage = oCommentList.find('.page'),
                        totalSize = msg.totalSize,
                        aCommentData = msg.commentData,
                        sCommentContentHtml = '';

                    //往刚插入总体框架的ul节点插入获得的评论数据
                    for ( var i = 0, iLen = aCommentData.length; i < iLen; i ++ ) {
                        sCommentContentHtml += getCommentContentHtml( aCommentData[i] );
                    }
                    oUl.html(sCommentContentHtml);

                    //更新页码
                    updatePage( oPage, totalSize, pageStep );
                    //oPage.html(msg.commentPageCode);
                } else {
                    window.globalLayer.openWarning({'autoClose':true, time: 2000, text:msg.description});
                }
            } else {
                window.globalLayer.openWarning({'autoClose':true, time: 2000, text:msg.description});
            }
        });
    }

    //更新讨论区页码
    function updatePage( parent, totalSize, pageStep ) {
        var oPrev = parent.find('a').eq(0),
            oNext = parent.find('a').eq(1);

        if ( totalSize <= 1 ) {
            parent.hide();
            return;
        }

        if ( pageStep <= 1 ) {
            oPrev.hide();
            oNext.show();
        } else if ( pageStep >= totalSize ) {
            oPrev.show();
            oNext.hide();
        } else {
            oPrev.show();
            oNext.show();
        }
    }


    //获取一条评论的html
    function getCommentContentHtml( data ) {
        return '<li cid="'+ data.cid +'" replayUserId="'+ data.userId +'">\
                        <div class="user-avatar"><a href="'+ data.commentAvatar +'"><img src="'+ data.commentAvatar +'" width="30" height="30"></a></div>\
                        <div class="con"  uid="'+ data.userId +'" cid="'+ data.cid +'" ugcId="'+ data.ugcId +'"  >\
                            <p>'+ (function() {
                var tmpStr = '';

                if ( data.commentReplyUserName ) {
                    tmpStr = '<span class="user-name"><a href="'+ data.commentUserUrl +'">'+ data.commentUserName +'</a>：</span>回复<span class="user-name"> <a href="'+ data.commentReplyUserUrl +'">'+ data.commentReplyUserName +'</a></span>';
                } else {
                    tmpStr = '<span class="user-name"><a href="'+ data.commentUserUrl +'">'+ data.commentUserName +'</a></span>';
                }
                return tmpStr;
            })() +'：'+ data.commentContent +'</p>\
                            <div class="w-opt"> <span class="time">'+ data.commentPublishTime +'</span> '+ (function() {
                //此处判断该条评论是否为当前用户所有，如果是，则输出删除功能，否则不输出
                return data.userId == userServers.getUserInfo().userId ? '<span class="js-remove-comment f-red"><a href="javascript:;">删除</a></span>' : '';
            })() +' '+ (function() {
                //此处判断该条评论是否为当前用户所有，如果是，则不输出回复功能，否则输出
                return data.userId != userServers.getUserInfo().userId ? '<span class="reply"><a href="javascript:;">回复</a></span>' : '';
            })() +' </div>\
                        </div>\
                    </li>';
    }


    //获取评论内容的盒子html
    function getCommentBoxHtml() {
        return '<div class="js-comment-content content">\
                        <div class="input-block textarea-block">\
                            <div class="textarea"><textarea class="js-cumment-input" name=""></textarea></div>\
                            <div class="button">\
                                <button type="button" class="js-cumment-button button-default button-disabled">评论</button>\
                            </div>\
                        </div>\
                        <div class="js-comment-list list">\
                            <ul></ul><!--此处ul里面放li，每条li代表一条评论-->\
                            <div class="page"><a href="javascript:;" class="pre">上一页</a><a href="javascript:;" class="next">下一页</a></div><!--此处放分页页码-->\
                        </div>\
                    </div>';
    }

    //是否自动打开评论区


    setTimeout( function (){
        autoOpen && autoOpenComment();
    },100);

};